
#ifndef __TERRAINGEOM_H__
#define __TERRAINGEOM_H__

#include "Geometry.h"

class SubLevelGeom;

class TerrainGeom : public Geometry
{
public:

	// Constructor
	TerrainGeom(Entity *_parent, vector<vector<uchar>> &hMap);
	TerrainGeom(Entity *_parent, vector<vector<uchar>> &hMap,
							ushort _numDivisions, Level _detail);

	// Creates subLevels
	void SetDetail(ushort _numDivisions, Level _detail);

	// Gets the height of the terrain, given a x & z
	float GetHeight(float x, float z);
	float GetHeight(const Real3 &pos) { return GetHeight(pos.x, pos.z); }

protected:

	// Detail level
	ushort numDivisions;
	Level detail;
	float sideLength;

	// Update frequency ????
	// ushort frequency; // in frames (actually period [1/f])
	
	// Sublevels
	vector<SubLevelGeom> subLevels;

	// Render
	void _Render(uchar renderFlag);

	// Create Main height map mesh
	void CreateHeightMap(vector<vector<uchar>> &hMap);
};

class SubLevelGeom : public Geometry
{
public:

	// Constructor
	SubLevelGeom(Mesh *hMap,
							 const Real3 &_center, float _sideLength, ushort _maxLevel, 
							 bool _isLeftEdge = false, bool _isRightEdge  = false, 
							 bool _isTopEdge  = false, bool _isBottomEdge = false);

	// Sets the level
	void SetLevel(ushort level);

	// Corrects Edges
	void CorrectLeftEdge();
	void CorrectRightEdge();
	void CorrectTopEdge();
	void CorrectBottomEdge();

protected:

	// Position variables
	Real3 center;
	float sideLength;

	// Detail level
	ushort maxLevel; // num splits in half
	ushort curLevel; // (max - cur) = splits
									 // higher number = lower detail
	ushort edgeDivisions; // 2 ^ (max - cur)

	// Max detail mesh
	Mesh maxMesh;

	// Edges of total terrain
	bool isLeftEdge   : 1;
	bool isRightEdge  : 1;
	bool isTopEdge    : 1;
	bool isBottomEdge : 1;

	// Corrected edges for boundry issues
	bool hasCorrectedLeftEdge   : 1;
	bool hasCorrectedRightEdge  : 1;
	bool hasCorrectedTopEdge    : 1;
	bool hasCorrectedBottomEdge : 1;

	// Render
	void _Render(uchar renderFlag);

	// Create Max Mesh
	void CreateMaxMesh(Mesh *hMap);

	friend class TerrainGeom;
};

#endif // __TERRAINGEOM_H__